package my.distributed;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.concurrent.atomic.AtomicInteger;

public class NodeDistributor
{
	private AtomicInteger nodeCount; 
	public NodeDistributor(int initialNodes)
	{
		nodeCount = new AtomicInteger(initialNodes);
	}
	
	public void AddNode()
	{
		nodeCount.addAndGet(1);
	}
	
	public void RemoveNode()
	{
		nodeCount.decrementAndGet();
	}
	
	//
	// Gets the node that the key 'k' is mapped to for putting or getting data
	//
	public long GetNode(String k)
	{
		return GetHashKey(k) % nodeCount.get();
	}

	/**
	 * Get the md5 of the given key.
	 */
	public static byte[] computeMd5(String k)
	{
		MessageDigest md5;
		try
		{
			md5 = MessageDigest.getInstance("MD5");
		} catch (NoSuchAlgorithmException e)
		{
			throw new RuntimeException("MD5 not supported", e);
		}
		md5.reset();
		md5.update(getKeyBytes(k));
		return md5.digest();
	}

	/**
	 * Get the bytes for a key.
	 * 
	 * @param k
	 *            the key
	 * @return the bytes
	 */
	public static byte[] getKeyBytes(String k)
	{
		try
		{
			return k.getBytes("UTF-8");
		} catch (UnsupportedEncodingException e)
		{
			throw new RuntimeException(e);
		}
	}

	public static long GetHashKey(String k)
	{
		long rv = 0;
		byte[] bKey = computeMd5(k);
		rv = ((long) (bKey[3] & 0xFF) << 24) | ((long) (bKey[2] & 0xFF) << 16)
				| ((long) (bKey[1] & 0xFF) << 8) | (bKey[0] & 0xFF);
		return rv & 0xffffffffL; /* Truncate to 32-bits */
	}
}
